﻿#region 命名空间

using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Threading.Tasks;
using Unity.Interception.PolicyInjection.Pipeline;

#endregion

namespace Sharp.Infrastructure.Crosscutting
{
    /// <summary>
    ///     日志处理器
    /// </summary>
    public class LoggingHandler : ICallHandler
    {
        /// <summary>
        ///     保存日志的委托
        /// </summary>
        /// <returns></returns>
        public delegate void SaveLoging(string log);

        /// <summary>
        ///     构造函数，此构造函数是用于Attribute调用
        /// </summary>
        /// <param name="message">消息</param>
        public LoggingHandler(string message)
        {
            Message = message;
        }

        /// <summary>
        ///     构造函数，此处不可省略，否则会导致异常
        /// </summary>
        /// <param name="attributes">配置文件中所配置的参数</param>
        public LoggingHandler(NameValueCollection attributes)
        {
            Order = Convert.ToInt32(attributes["Order"]);
            Message = String.IsNullOrEmpty(attributes["Message"]) ? "" : attributes["Message"];
        }

        /// <summary>
        ///     保存日志
        /// </summary>
        public static SaveLoging LoginFunc { get; set; }

        /// <summary>
        ///     事件
        /// </summary>
        public string Message { get; set; }

        /// <inheritdoc />
        /// <summary>
        ///     实现ICallHandler.Invoke方法，用于对具体拦截方法做相应的处理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input == null) throw new ArgumentNullException(nameof(input));
            if (getNext == null) throw new ArgumentNullException(nameof(getNext));

            //调用具体方法
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                return result;
            }

            var res = result.ReturnValue as Result;
            if (res != null && res.Err.Length > 0)
            {
                return result;
            }

           //var userId = HttpContext.Current.User.Identity.GetUserId();
           //var fullName = ContactContext.Current.UserName;
           Task.Run(() =>
            {
                if (Message.Contains("@p") && input.Inputs.Count > 0 && input.Arguments.Count > 0)
                {
                    TextTemplate temp = new TextTemplate
                    {
                        Inputs = input.Inputs
                    };
                    temp.Convert(Message);
                    
                    foreach (var x in temp.Params)
                    {
                        Message = Message.Replace(x.Key, x.Value);
                    }
                }
                else if (Message.Length == 0 && res != null && !res.LogMessage.IsNullOrEmpty())
                {
                    Message = res.LogMessage;
                }

                //UserLog model = new UserLog
                //{
                //    UserId = userId,
                //    FullName = fullName,
                //    Event = "",
                //    Content = Message,
                //    InternalSources = input.Target.ToString()
                //};
                ////如果调用方法没有出现异常则记录操作日志
                //if (LoginFunc != null)
                //{
                //    LoginFunc.Invoke(model.ToJson());
                //}
                //else
                //{
                //    using (var proxy = new ServiceProxy<IUserService>())
                //    {
                //        proxy.Channel.SaveLog(model.ToJson());
                //    }
                //}
        });

            return result;
        }

        /// <summary>
        ///     排序
        /// </summary>
        public int Order { get; set; }

        public class UserLog : IUserLog
        {
            /// <summary>
            /// 操作员Id
            /// </summary>
            public int UserId { get; set; }

            /// <summary>
            /// 操作员姓名
            /// </summary>
            public string FullName { get; set; }

            /// <summary>
            /// 操作内容的描述
            /// </summary>
            public string Content { get; set; }

            /// <summary>
            /// 事件
            /// </summary>
            public string Event { get; set; }

            /// <summary>
            /// 事件时间
            /// </summary>
            public DateTime Eventtime { get; set; }

            /// <summary>
            /// 内部来源
            /// </summary>
            public string InternalSources { get; set; }
            /// <summary>
            /// 外部来源
            /// </summary>
            public string ExternalSources { get; set; }

            /// <summary>
            ///     获取当前领域实体类的全局唯一标识。
            /// </summary>
            public int Id { get; set; }
        }
    }


}